<?php
/*
 * Gallery - a web based photo album viewer and editor
 * Copyright (C) 2000-2007 Bharat Mediratta
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA  02110-1301, USA.
 */

/**
 * Variable column theme based on ICE with intention to emulate look and feel of Apples .Mac gallery.
 * @package Themes
 * @subpackage PEAR
 * @author Fredrik Erlandsson (fredrik.e@gmail.com)
 * @version $Revision: 1
 */

class PearTheme extends GalleryTheme {

    /**
     * Constructor
     */
    function PearTheme() {
	global $gallery;

	$this->setId('pear');
	$this->setName($gallery->i18n('.Pear'));
	$this->setDescription($gallery->i18n('Look and Feel like Apples .Mac\'s gallery'));
	$this->setVersion('1.0');
	$this->setRequiredCoreApi(array(7, 10));
	$this->setRequiredThemeApi(array(2, 5));
	$this->setStandardSettings(
	    array(
		'showImageOwner' => 0, 
		'showAlbumOwner' => 0,
		'showItemTitle' => 1,
		'showItemSummaries' => 0,
		'showViewCount' => 0,
		'showDate' => 0,
		'showSize' => 0,
		'childsFloatingThumbsSize' => 200,
		'photoDescription' => 1,		
		'photoProperties' => 1, 
		'fullSize' => 1,
		'showPhotoSizes' => 0,
		'showImageSize' => 0,
		'disableViewInlineFullSize' => 1,
		'titlenavigation' => '',
		'titleblocks' => '',
		'titlealbum' => '',
		'titlephoto' => '',
		'titleextra' => '',
		'photoalbum' => '',
		'skimNo' => '50',
		'showLogo' => 1));
    }

    /**
     * @see GalleryTheme::getSettings()
     */
    function getSettings($itemId=null) {

	list ($ret, $settings, $params) = parent::getSettings($itemId);
	if ($ret) {
	    return array($ret, null, null);
	}

	/* Add in our custom settings */
	$titledivstart = '<div><br><br><b><i>';	
	$titledivend = '</i></b></div>';

      	/* Get is user admin */
        $userIsAdmin = GalleryCoreApi::assertUserIsSiteAdministrator();
                            
	/* Extra Link and Copyright settings */			
	if (!$userIsAdmin) {
	    	$settings[] = array('key' => 'titleextra',
				    'name' => $titledivstart . $this->translate('.PEAR : Pear settings') . $titledivend,
				    'type' => '',
            'value' => $params['titleextra']);
	
	/* Number of images in skimm */
	$settings[] = array('key' => 'skimNo',
					'name' => $this->translate('Number of images per skimming Album.'),
					'type' => 'text-field',
					'value' => $params['skimNo']);

	/* Show image size */
	$settings[] = array('key' => 'showMosaic',
			    'name' => $this->translate('Start in Mosaic View.'),
			    'type' => 'checkbox',
			    'value' => $params['showMosaic']);		
	$settings[] = array('key' => 'showLogo',
			    'name' => $this->translate('Show pear logo in footer.'),
			    'type' => 'checkbox',
			    'value' => $params['showLogo']);		
}	

	/* Album settings */
	$settings[] = array('key' => 'titlealbum',
			    'name' => $titledivstart . $this->translate('ALBUM : Settings applied to the Grid view') . $titledivend,
			    'type' => '',
                	    'value' => $params['titlealbum']);

    	$settings[] = array('key' => 'showCoreItemLinks',
			    'name' => $this->translate('Show item links (Album)'),
			    'type' => 'checkbox',
			    'value' => $params['showCoreItemLinks']);

    	$settings[] = array('key' => 'showItemTitle',
			    'name' => $this->translate('Show item title (Album)'),
			    'type' => 'checkbox',
			    'value' => $params['showItemTitle']);		
                
    	$settings[] = array('key' => 'showItemSummaries',
			    'name' => $this->translate('Show item summaries (Album)'),
			    'type' => 'checkbox',
			    'value' => $params['showItemSummaries']);		

	/* Show item details on album pages */
	$settings[] = array('key' => 'itemDetails',
			    'name' => $this->translate('Show item details (Album)'),
			    'type' => 'checkbox',
			    'value' => $params['itemDetails']);	
			    
	/* Show date */
	$settings[] = array('key' => 'showDate',
			    'name' => $this->translate('Show item date (Album)'),
			    'type' => 'checkbox',
			    'value' => $params['showDate']);
			    
	/* Show size */
	$settings[] = array('key' => 'showSize',
			    'name' => $this->translate('Show item size (Album)'),
			    'type' => 'checkbox',
			    'value' => $params['showSize']);

	$settings[] = array('key' => 'showViewCount',
			    'name' => $this->translate('Show item view count (Album)'),
			    'type' => 'checkbox',
			    'value' => $params['showViewCount']);
			    		
	/* Photo settings */
	$settings[] = array('key' => 'titlephoto',
			    'name' => $titledivstart . $this->translate('PHOTO : Settings applied to Photo view') . $titledivend,
			    'type' => '',
                	    'value' => $params['titlephoto']);
	    				
	$settings[] = array('key' => 'photoDescription',
			    'name' => $this->translate('Show photo descriptions'),
			    'type' => 'checkbox',
			    'value' => $params['photoDescription']);
			    
	$settings[] = array('key' => 'photoProperties',
			    'name' => $this->translate('Show \'Photo Properties\' icon'),
			    'type' => 'checkbox',
			    'value' => $params['photoProperties']);
	
	$settings[] = array('key' => 'fullSize',
			    'name' => $this->translate('Show \'Full Size\' icon'),
			    'type' => 'checkbox',
			    'value' => $params['fullSize']);

	$settings[] = array('key' => 'showPhotoSizes',
			    'name' => $this->translate('Show photo sizes'),
			    'type' => 'checkbox',
			    'value' => $params['showPhotoSizes']);

        /* Disable view image inline full size */
        $settings[] = array('key' => 'disableViewInlineFullSize',
	                    'name' => $this->translate('Disable view image inline full size'),
	                    'type' => 'checkbox',
	                    'value' => $params['disableViewInlineFullSize']);

	return array(null, $settings, $params);
    }

    /**
     * @see GalleryTheme::validateSettings
     */
    function validateSettings($settings) {
	$error = parent::validateSettings($settings);
	
	if (empty($settings['skimNo']) || !is_numeric($settings['skimNo'])) {
		$error['skimNo'] = $this->translate('You must enter a number greater than 0');
	}

	return $error;
    }

    /**
     * @see GalleryTheme::showAlbumPage
     */
    function showAlbumPage(&$template, $item, $params, $childIds) {
	$ret = $this->loadCommonTemplateData(
	    $template, $item, $params,
	    array('owner', 'viewCount', 'childCount', 'descendentCount', 'parents',
		  'systemLinks', 'itemLinks', 'itemSummaries', 'permissions',
		  'thumbnails', 'pageNavigator', 'jumpRange'),
	     $childIds);
	if ($ret) {
	    return array($ret, null);
	}

	/* Load custom style if the theme supports them (and they're available)  */
	$ret = $this->loadCustomStyle($template, $item, $params);
	if ($ret) {
	    return array($ret, null);
	}
	
	/* Add in our extra stuff */
	$theme =& $template->getVariableByReference('theme');
	$theme['columnWidthPct'] = floor(100 / $params['columns']);

	foreach ($theme['children'] as $i => $child) {
		//if the child has children items (i.e. it's a gallery itself and not just a photo)
		if ($child['canContainChildren']) {
			$theme['children'][$i]['grandChild'] = $this->getThumbsForAlbum($child['id'], $params['skimNo']);
		}
	}
	
	/* Add resizedId to child values, required for Lightbox JS */
	if ( $theme['children'] ){
		foreach ( $theme['children'] as $key => $value ){
			if ( $value['id'] ){
				list($ret,$resizedIds) =  
					GalleryCoreApi::fetchResizesByItemIds(array($value['id']));
				if ($ret)
					return $ret;
			}
			$theme['children'][$key]['resizedId'] = $value['id'];
			if ( $resizedIds ){
				/* Find the best resized option
				 * 
				 * Use width/height max=800; */
				$lboxMaxEdge = 800;
				$resizedEdge = NULL;
				$resizedId = NULL;
				$resizedRatio = NULL;
				$resizedWidth = NULL;
				$resizedHeight = NULL;
				foreach ( $resizedIds[$value['id']] as $resize ){
					$width = $resize->getWidth();
					$height = $resize->getHeight();
					$edge = ( $width > $height )? $width : $height;
					if ( $edge <= $lboxMaxEdge ){
						if ( !isset($resizedEdge) ){
							$resizedId = $resize->getId();
							$resizedEdge = $edge;
							$resizedRatio = $width / $height;
							$resizedWidth = $width;
							$resizedHeight = $height;
						} else if ( $edge > $resizedEdge ){ 
							$resizedId = $resize->getId();
							$resizedEdge = $edge;
							$resizedRatio = $width / $height;
							$resizedWidth = $width;
							$resizedHeight = $height;
						} 
					}
				}
				$theme['children'][$key]['resizedId'] = $resizedId;
				$theme['children'][$key]['resizedRatio'] = $resizedRatio;
				$theme['children'][$key]['resizedWidth'] = $resizedWidth;
				$theme['children'][$key]['resizedHeight'] = $resizedHeight;
			}
		}
	}
	/* end add resizedId to child values, required for Lightbox JS */

	/* Add our header and styles */
	return array(null, 'theme.tpl');
    }


	function getThumbsForAlbum($galleryAlbumItemID, $numThumbs) {
		$childData = array();
		list ($ret, $galleryAlbumItem) = GalleryCoreApi::loadEntitiesById($galleryAlbumItemID);
		if (! GalleryUtilities::isA($galleryAlbumItem, 'GalleryAlbumItem')) {
//			echo "not a gallery Album Item!<br>";
		}
		//get its childrenIds
		list ($ret, $childrenIds) = GalleryCoreApi::fetchChildItemIds($galleryAlbumItem, null, $numThumbs);
		if ($ret) {
//			echo "could not get child item ids<br>";
		}
		//load those children as GalleryItems themselves (and not just the Ids returned above)
		list ($ret, $childrenItems) = GalleryCoreApi::loadEntitiesById($childrenIds);
		if ($ret) {
//				echo "could not get children items<br>";
		}

		//get the thumbnails for those items
		list ($ret, $thumbnails) = GalleryCoreApi::fetchThumbnailsByItemIds($childrenIds);
		if ($ret) {
//			echo "could not fetch thumbnails<br>";
		}
		
		//loop through each child
		foreach ($childrenItems as $i) {

			//get the data of the child object into an array called childData
			$childData[$i->getId()] = (array)$i;//$child->getMemberData();
			//add the thumbnail information for this child object to that array
			//$childData[$i]['thumbnail'] = $thumbnails[$childData[$i]['id']]->getMemberData();
			if(isset($childData[$i->getId()])) {
				$childData[$i->getId()]['thumbnail'] = (array)$thumbnails[$i->getId()];
				}
		}
		return $childData;
	}


    /**
     * @see GalleryTheme::showPhotoPage
     */
    function showPhotoPage(&$template, $item, $params) {
	
	$dataTypes = array('owner', 'parents', 'systemLinks', 'itemLinks', 'permissions',
			   'itemLinksDetailed', 'itemNavigator', 'imageViews');
	$ret = $this->loadCommonTemplateData($template, $item, $params, $dataTypes);
	if ($ret) {
	    return array($ret, null);
	}

	/* Load custom style if the theme supports them (and they're available)  */
	$ret = $this->loadCustomStyle($template, $item, $params);
	if ($ret) {
	    return array($ret, null);
	}
	
	$theme =& $template->getVariableByReference('theme');
		
	/* Load brothers to $item (overloads LoadPeers) */
	if (isset($theme['item']['parent']->getChildrenFunction)) {
		$parent = $theme['item']['parent'];
		list ($ret, $peerIds) = call_user_func($parent->getChildrenFunction, $theme['actingUserId']);
		if ($ret) {
			return $ret;
		}
	} else if ($theme['item']['parentId'] > 0) {
		list ($ret, $canViewParent) =
		GalleryCoreApi::hasItemPermission($theme['item']['parentId'], 'core.view',  $theme['actingUserId']);
		if ($ret) {
			return $ret;
		}
		if ($canViewParent) {
			list ($ret, $parent) = GalleryCoreApi::loadEntitiesById($theme['item']['parentId']);
			if ($ret) {
				return $ret;
			}
			list ($ret, $peerIds) =
			GalleryCoreApi::fetchChildItemIds($parent, null, null,  $theme['actingUserId']);
			if ($ret) {
				return $ret;
			}
		}
	}
	if (!empty($peerIds)) {
		foreach ($peerIds as $i => $id) {
			if ($id == $theme['item']['id']) {
				$peerItemIndex = $i;
				break;
			}
		}
	}
	if (isset($peerItemIndex)) {
		$windowSize = 50;
		$peerLast = count($peerIds) - 1;
		$peerNeighborStart = max($peerItemIndex - (int)($windowSize/2), 0);
		$peerNeighborEnd = min($peerItemIndex + (int)(($windowSize+1)/2), $peerLast);
		/* If the window is pinned to one end, expand it to the entire windowSize */
		if ($peerNeighborStart == 0) {
			$peerNeighborEnd = min($peerLast, $windowSize);
		} else if ($peerNeighborEnd == $peerLast) {
			$peerNeighborStart = max($peerLast - $windowSize, 0);
		}
		if ($peerNeighborStart > 0 && $addEnds) {
			$peerMap[0] = $peerIds[0];
		}
		for ($i = $peerNeighborStart; $i <= $peerNeighborEnd; $i++) {
			$peerMap[$i] = $peerIds[$i];
		}
		if ($peerNeighborEnd < $peerLast && $addEnds) {
			$peerMap[$peerLast] = $peerIds[$peerLast];
		}
		
		list ($ret, $peerItems) = GalleryCoreApi::loadEntitiesById($peerMap);
		if ($ret) {
			return $ret;
		}
		if (!empty($params['loadThumbnails'])) {
			list ($ret, $thumbTable) = GalleryCoreApi::fetchThumbnailsByItemIds($peerMap);
			if ($ret) {
				return $ret;
			}
		}
		$j = 0;
		foreach ($peerMap as $i => $id) {
			$peer = (array)$peerItems[$j++];
			$peer['peerIndex'] = $i + 1;
			if (isset($thumbTable[$id])) {
				$peer['thumbnail'] = (array)$thumbTable[$id];
			}
			$peers[] = $peer;
		}
		$theme['brothers'] = array('peers' => $peers,
								 'peerCount' => count($peerIds), 'thisPeerIndex' => $peerItemIndex + 1,
								 'parent' => (array)$parent);
	} else {
		$theme['brothers'] =
		array('peers' => array(), 'peerCount' => 0);
	}
	
	/* Add resizedId to child values, required for Lightbox JS */
	foreach ( $theme['brothers']['peers'] as $key => $value ){
		if ( $value['id'] ){
			list($ret,$resizedIds) =  
			GalleryCoreApi::fetchResizesByItemIds(array($value['id']));
			if ($ret)
			return $ret;
		}
		$theme['brothers']['peers'][$key]['resizedId'] = $value['id'];
		if ( $resizedIds ){
			/* Find the best resized option
			 * 
			 * Use width/height max=800; */
			$lboxMaxEdge = 800;
			$resizedEdge = NULL;
			$resizedId = NULL;
			foreach ( $resizedIds[$value['id']] as $resize ){
				$width = $resize->getWidth();
				$height = $resize->getHeight();
				$edge = ( $width > $height )? $width : $height;
				if ( $edge <= $lboxMaxEdge ){
					if ( !isset($resizedEdge) ){
						$resizedId = $resize->getId();
						$resizedEdge = $edge;
					} else if ( $edge > $resizedEdge ){ 
						$resizedId = $resize->getId();
						$resizedEdge = $edge;
					} 
				}
			}
			$theme['brothers']['peers'][$key]['resizedId'] = $resizedId;
		}
	}
	/* end add resizedId to child values, required for Lightbox JS */
	
	
	return array(null, 'theme.tpl');
    }

    /**
     * @see GalleryTheme::showModulePage
     */
    function showModulePage(&$template, $item, $params, $templateFile) {
	
	$ret = $this->loadCommonTemplateData(
	    $template, $item, $params, array('parents', 'systemLinks'));
	if ($ret) {
	    return array($ret, null);
	}

	return array(null, 'theme.tpl');
    }

    /**
     * @see GalleryTheme::showAdminPage
     */
    function showAdminPage(&$template, $item, $params, $templateFile) {
	
	$ret = $this->loadCommonTemplateData(
	    $template, $item, $params, array('parents', 'systemLinks'));
	if ($ret) {
	    return array($ret, null);
	}

	return array(null, 'theme.tpl');
    }

    /**
     * @see GalleryTheme::showErrorPage
     */
    function showErrorPage(&$template) {
	return array(null, 'error.tpl');
    }

    /**
     * @see GalleryTheme::showProgressBarPage
     */
    function showProgressBarPage(&$template, $item, $params) {
	$ret = $this->loadCommonTemplateData(
	    $template, $item, $params, array('parents', 'systemLinks'));
	if ($ret) {
	    return array($ret, null);
	}

	return array(null, 'theme.tpl');
    }
	
    /**
     * @see Load custom style if the theme supports them (and they're available) 
     */
    function loadCustomStyle(&$template, $item, $params) {
	if (!empty($params['customstyle'])) {
	    list ($ret, $customstyle) = GalleryCoreApi::newFactoryInstance('CustomStyleInterface_1_0');
	    if ($ret) {
		return array($ret, null);
	    }
	    if (isset($customstyle)) {
		$ret = $customstyle->selectCustomStyle($template, $params['customstyle']);
		if ($ret) {
		    return array($ret, null);
		}
	    }
	}
     }
     
    /**
     * @see GalleryPlugin::upgrade
     */
    function upgrade($currentVersion) {
	if (isset($currentVersion) && version_compare($currentVersion, '0.2', '<')) {
                list ($ret, $itemIds) = GalleryCoreApi::fetchAllItemIds('GalleryAlbumItem');
                if ($ret) {
                    return $ret;
                }
                
                foreach ($itemIds as $itemId) {
                        list ($ret, $value) = GalleryCoreApi::getPluginParameter('theme', 'pear', 'childsFloating', $itemId);
                        if ($ret) {
                            return $ret;
                        }
                }
           
                /* Remove 'childsFloating' parameter */
                foreach (array('childsFloating') as $param) {
                    if (isset($params[$param])) {
                        $ret = $this->removeParameter($param);
                        if ($ret) {
                            return $ret;
                        }
                    }
                }
	}
	return null;
    }
}
?>
